<template>
  <div class="container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card class="box-card">

      <!-- 提示消息 -->
      <el-alert
        title="添加商品消息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>

      <!-- 步骤条 -->
      <el-steps
        :active="indexActive - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form
        :model="addGoodsForm"
        :rules="addGoodsFormRules"
        ref="addGoodsFormRef"
        label-position="top"
      >
        <!-- 侧边导航 -->
        <el-tabs
          :tab-position="'left'"
          v-model="indexActive"
          :before-leave="BeforeLeave"
          @tab-click="tabClick(indexActive)"
        >
          <!-- 基本信息 B -->
          <el-tab-pane
            label="基本信息"
            name="0"
          >

            <el-form-item
              label="商品名称"
              prop="goods_name"
            >
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>

            <el-form-item
              label="商品价格"
              prop="goods_price"
            >
              <el-input
                type="number"
                v-model="addGoodsForm.goods_price"
              ></el-input>
            </el-form-item>

            <el-form-item
              label="商品重量"
              prop="goods_weight"
            >
              <el-input
                type="number"
                v-model="addGoodsForm.goods_weight"
              ></el-input>
            </el-form-item>

            <el-form-item
              label="商品数量"
              prop="goods_number"
            >
              <el-input
                type="number"
                v-model="addGoodsForm.goods_number"
              ></el-input>
            </el-form-item>

            <el-form-item
              label="商品分类"
              prop="goods_cat"
            >
              <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="catelist"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>

          </el-tab-pane>
          <!-- 基本信息 E -->

          <el-tab-pane
            label="商品参数"
            name="1"
          >
            <el-form-item
              :label="item.attr_name"
              v-for="(item,i) in manyData"
              :key="i"
            >

              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  size="mini"
                  :label="bb"
                  v-for="(bb,j) in item.attr_vals"
                  :key="j"
                  border
                  :v-model="true"
                ></el-checkbox>
              </el-checkbox-group>

            </el-form-item>

          </el-tab-pane>
          <el-tab-pane
            label="商品属性"
            name="2"
          >

            <el-form-item
              :label="item.attr_name"
              v-for="(item,i) in onlyData"
              :key="i"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>

          </el-tab-pane>
          <el-tab-pane
            label="商品图片"
            name="3"
          >
            <el-upload
              :action="uploadUrl"
              :headers="uploadHeaders"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture"
            >
              <el-button
                size="small"
                type="primary"
              >点击上传</el-button>
              <div
                slot="tip"
                class="el-upload__tip"
              >只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>

          </el-tab-pane>
          <el-tab-pane
            label="商品内容"
            name="4"
          >

            <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
            <el-button
              type="primary"
              class="Addbtn"
              @click="addForm('addGoodsFormRef')"
            >添加商品</el-button>
          </el-tab-pane>

        </el-tabs>

      </el-form>

    </el-card>

    <!-- 图片预览 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewImgVisible"
      width="50%"
    >
      <img
        :src="previewPath"
        alt=""
        class="previewImg"
      >
    </el-dialog>

  </div>
</template>

<script>
import _ from 'loadsh'

export default {
  name: '',
  data() {
    return {
      indexActive: '0',
      addGoodsForm: {
        'goods_name': '商品1',
        'goods_price': 10,
        'goods_number': 10,
        'goods_weight': 10,
        'goods_cat': '1,2,3',
        'pics': [], // 上传的图片临时路径
        'goods_introduce': '', // 商品内容介绍
        'attrs': [] // 商品的参数
      },
      // 表单验证规则
      addGoodsFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请输入商品分类', trigger: 'blur' }
        ]
      },
      // 商品分类数据列表
      catelist: [],
      cateProps: {
        'expandTrigger': 'hover',
        'value': 'cat_id',
        'label': 'cat_name',
        'children': 'children'
      },
      // 商品参数数据
      manyData: [],
      // 商品属性数据
      onlyData: [],
      // 上传地址
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 上传请求头
      uploadHeaders: {
        'Authorization': window.sessionStorage.getItem('token')
      },
      previewPath: '',
      previewImgVisible: false
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据列表
    async getCateList() {
      const { data: res } = await this.$axios.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.catelist = res.data

    },
    handleChange(value) {
      // console.log(value)
      // console.log(this.addGoodsForm.goods_cat.join(','))
      if (value.length !== 3) {
        this.addGoodsForm.goods_cat = ''
      }

      // console.log(this.cate_id)
    },
    BeforeLeave(activeName, oldActiveName) {
      // console.log('即将离开',oldActiveName)
      // console.log('即将进入',activeName)
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    async getCateData(sel) {
      const { data: res } = await this.$axios.get(`categories/${this.cate_id}/attributes`, {
        params: { 'sel': sel }
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      if (sel === 'many') {
        res.data.forEach(item => {
          // console.log(item)
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
      }
      this[sel + 'Data'] = res.data
      console.log(res.data)
    },
    async tabClick(i) {
      console.log(i)
      // 获取动态商品参数数据
      if (i === '1') {
        this.getCateData('many')
      } else if (i === '2') {
        this.getCateData('only')
      }
    },
    // 删除上传图片的操作
    handleRemove(file, fileList) {
      // console.log(file, fileList);
      // console.log(file);
      const filePath = file.response.data.tmp_path
      // console.log(filePath)

      // const i = this.addGoodsForm.pics.findIndex(item => item.pic === filePath)

      const i = this.addGoodsForm.pics.findIndex((item, index) => {
        if (item.pic === filePath) {
          return index
        }
      })
      this.addGoodsForm.pics.splice(i, 1)
    },
    // 预览上传图片后的效果
    handlePreview(file) {
      // console.log(file.response.data.url);
      this.previewPath = file.response.data.url
      this.previewImgVisible = true
    },
    // 图片上传成功的事件
    handleSuccess(response, file, fileList) {
      // console.log(response, file, fileList);
      // tmp_path
      let piscInfo = { 'pic': response.data.tmp_path }
      this.addGoodsForm.pics.push(piscInfo)

      // console.log(this.addGoodsForm)
    },
    // 添加商品
    addForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (!valid) return this.$message.error('请填写必填的选项')
        // console.log(this.addGoodsForm.goods_cat)

        // 商品参数数据
        this.manyData.forEach(item => {
          console.log(item)
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addGoodsForm.attrs.push(newInfo)
        })
        // 商品属性数据
        this.onlyData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addGoodsForm.attrs.push(newInfo)
        })

        // 深拷贝
        const form = _.cloneDeep(this.addGoodsForm)
        form.goods_cat = form.goods_cat.join(',')
        console.log(form)

        const { data: res } = await this.$axios.post('goods',form)

        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.$router.push('/goods')

        console.log(res.data)


      })
    }
  },
  computed: {
    // 三级商品的id
    cate_id() {
      if (this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="scss" scoped>
.el-checkbox {
  margin: 0 0 10px 10px;
}
.previewImg {
  max-width: 100%;
  margin: 0 auto;
  display: block;
}
.Addbtn {
  margin-top: 15px;
}
</style>